package com.hunk.maven_web_test.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.hunk.maven_web_test.domin.User;
import com.hunk.maven_web_test.web.Response;

/**返回为jsp的controller类
 * @author HunkDeng
 *
 */
@Controller
@RequestMapping("/user")
public class UserConroller {
	/**返回jsp页面
	 * @return
	 */
	@RequestMapping(value="/index")
	public String index() {
		return "user/index";
	}

	/**处理form表单并返回success页面或failed页面
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/login",method=RequestMethod.POST)
	public ModelAndView login(@ModelAttribute("user")User user) {
		if ("hunk".equals(user.getUserName())) {
			if ("hunk".equals(user.getPassword())) {
				ModelAndView mav = new ModelAndView();
				mav.setViewName("user/login_success");
				mav.addObject(user);
				return mav;
			}
		}
		ModelAndView mav = new ModelAndView();
		mav.setViewName("user/login_failed");
		return mav;
	}
	
	@RequestMapping(value = "/login3")
	public void login3(@ModelAttribute("user")User user, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		if ("hunk".equals(user.getUserName())) {
			if ("hunk".equals(user.getPassword())) {
				out.append("success");
				return;
			}
		}
		out.append("failed");
	}
	
	/** 测试requestparam的入参是否检查
	 *  并查看错误信息
	 * @param id
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/login2",method=RequestMethod.POST)
	public ModelAndView login2(
				@RequestParam(value="id",required=true)String id,
				@ModelAttribute("user")User user) {
		if ("hunk".equals(user.getUserName())) {
			if ("hunk".equals(user.getPassword())) {
				ModelAndView mav = new ModelAndView();
				mav.setViewName("user/login_success");
				mav.addObject(user);
				return mav;
			}
		}
		ModelAndView mav = new ModelAndView();
		mav.setViewName("user/login_failed");
		return mav;
	}
	@RequestMapping(value="/showUserInManyWays")
	public String showUserInManyWays(ModelMap mm) {
		User user = new User();
		user.setUserName("hunk");
		user.setPassword("psd");
		
		
		User user2 = new User();
		user2.setUserName("hunk2");
		user2.setPassword("psd");
		
		Response res = new Response();
		res.getList().add(user);
		res.getList().add(user2);
		mm.addAttribute("baseResponse", res);
		return "user/showUserInManyWays";
	}
}
